package com.security.securityproject.service.serviceImpl;

import com.security.securityproject.entity.SysUser;
import com.security.securityproject.mapper.SysUserMapper;
import lombok.extern.java.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.lang.model.element.VariableElement;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * @author huangkf
 * @version 1.0
 * @date 2022/11/29 : 23:38
 * @description 权限用户封装实现类
 */


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private final static Logger LOGGER = LoggerFactory.getLogger(UserDetailsServiceImpl.class);


    @Autowired
    private PasswordEncoder passwordEncoder;


    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        SysUser byUserName = sysUserMapper.findByUserName(username);
        if (byUserName == null) {

            LOGGER.info("用户名不存在"+byUserName);
         throw   new UsernameNotFoundException("用户名不存在！");
        }
        String encode = passwordEncoder.encode(byUserName.getPassWord());
            LOGGER.info("加密之后的密码为："+encode);
        //2.4 因为权限字符拼接非常麻烦，所以spring security提供了AuthorityUtils工具类，帮我们封装，参数就是权限字符通过逗号分隔，比如"admin1,admin2"
        //权限配置 该用户所具有的的权限
        //通过ROLE_角色的名字区分角色和权限
     //   List<GrantedAuthority> grantedAuthorities1 = AuthorityUtils.commaSeparatedStringToAuthorityList("admin1,admin2,ROLE_superAdmin");
        //根据 用户Id封装权限和角色
        List<String> roles = sysUserMapper.hasRoles(byUserName.getUserId());
        List<String> permissionMenus = sysUserMapper.hasPermissionMenus(byUserName.getUserId());
        //拼接角色和权限
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < roles.size(); i++) {
            if (i == roles.size() - 1) {
                //如果没有权限字符，那么末尾不加逗号，如果有权限字符，末尾加逗号
                if(permissionMenus.size()>0) sb.append("ROLE_"+roles.get(i)+",");
                else sb.append("ROLE_"+roles.get(i));
                sb.append("ROLE_"+roles.get(i)).append(",");
            }


        }

        for (int i = 0; i < permissionMenus.size(); i++) {
            if (i == permissionMenus.size() - 1) {
                sb.append(permissionMenus.get(i));
            } else {
                sb.append(permissionMenus.get(i)).append(",");
            }
        }
        //封装权限
     List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(sb.toString());
        System.out.println("获取到的角色和权限为："+grantedAuthorities);

        User user = new User(username,encode,grantedAuthorities);
        return user;
    }
}
